﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Data.SqlClient;

namespace AsyncWebStudy.Controllers
{
    public class AsyncHomeController : AsyncController
    {
        //
        // GET: /AsyncHome/

        public async Task<ActionResult> IndexAsync()
        {
            string content = DateTime.Now.ToString("mm:ss:fff <br/>");

            using (SqlConnection connection =
                       new SqlConnection(GetConnectionString()))
            {
                var insertTask = RunCommandAsynchronously("insert into Tests (InsertTime) values ('" + DateTime.Now.ToShortDateString() + "')", connection);
                await Task.WhenAll(insertTask);

                content += insertTask.Result > 0 ? "成功" : "失败";
            }

            return Content(content + DateTime.Now.ToString("<br/> mm:ss:fff"));
        }

        private static Task<int> RunCommandAsynchronously(
            string commandText, SqlConnection connection)
        {
            SqlCommand command = new SqlCommand(commandText, connection);
            connection.Open();

            return command.ExecuteNonQueryAsync();
        }

        private static string GetConnectionString()
        {
            return @"Data Source=(LocalDB)\v11.0;AttachDbFilename=E:\Coding\Happy\Tools\AsyncWebStudy\AsyncWebStudy\App_Data\Test.mdf;Integrated Security=True";
        }
    }
}
